const request = (url, method, data) => {
	return new Promise((resolve, reject) => {
		// uni.showLoading()
		let token = uni.getStorageSync('api_token');
		uni.request({
			url: getApp().globalData.apiBase + url,
			method: method,
			data: data,
			header: {
				'content-type': 'application/json',
				'X-Auth-Token': token
			},
			success: res => {
				if (!res.data.code && res.statusCode == 200) {
					resolve(res.data);
				} else {
					// if (token && res.statusCode == 403) {
					// 	uni.removeStorageSync('api_token')
					// 	uni.reLaunch({
					// 		url: '/pages/index/index'
					// 	})
					// }
					if (token && res.data.message) {
						if (res.data.message == 'Username could not be found.') {
							uni.removeStorageSync('api_token')
							uni.switchTab({
								url: '/pages/index/index.vue'
							})
						}
						if (res.data.message == 'Entity is not found') {
							console.log('error', res)
							uni.hideLoading()
							uni.showModal({
								title: '提示',
								content: '您找的东西被外星人挟持了',
								showCancel: false,
								success: (data) => {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							})
							return;
						}
						if (res.data.message == 'Error while generating verification code!') {
							uni.showToast({
								title: '获取短信失败',
								icon: 'none'
							})
							uni.hideLoading()
							return;
						}
						uni.showModal({
							title: '提示',
							content: res.data.message,
							showCancel: false
						})
					} else {

					}
					reject(res.data.message);
				}
			},
			error: err => {
				reject('Network error');
			}
		})
	})
}

export default {
	get: (url, data) => request(url, 'GET', data),
	put: (url, data) => request(url, 'PUT', data),
	post: (url, data) => request(url, 'POST', data),
	delete: (url, data) => request(url, 'DELETE', data),
}
